var Q = require("q");
var crypto = require('crypto');
var MysqlService = require("./MysqlService.js");
var mysqlService = new MysqlService();
var McryptService = require("./McryptService.js");
var mcryptService = new McryptService();
var loginKey = "@#@vvtool$$$$$$520";

module.exports = UserService

function UserService(){

}


UserService.prototype.reg = function(map){
    var defered = Q.defer();
    var user = {}
    user.email = map.email;
    user.password = map.password;
    user.create_time = parseInt( (new Date().getTime()) /1000);

    mysqlService.insertJson("user",user).then(function(rows){
        if(typeof(rows)=="object" && rows.insertId>0){
            defered.resolve(rows.insertId);
        }else{
            defered.reject("注册失败");
        }
    });

    return defered.promise;
}

UserService.prototype.login = function(map){
    var time = (new Date().getTime())/1000;
    var email = map.email;
    var uid = map.uid;
    var sign = crypto.createHash('md5').update(loginKey+time+email, 'utf8').digest("hex");

    loginResult = {};
    loginResult.sign = sign;
    loginResult.time = time;
    loginResult.status = 1;
    loginResult.uidCrypt = mcryptService.encode(uid+"");
    loginResult.uid = uid;
    loginResult.msg = "登录成功";
    return loginResult;
}

UserService.prototype.checkPassword = function(map){
    var defered = Q.defer();

    var email = map.email;
    var password = map.password;
    var result = {}

    mysqlService.select("select * from user where email='"+email+"' limit 1",user).then(function(rows){
        if(rows.length>0 && rows[0]!=undefined){
            if(rows[0]["password"].toLowerCase()==password.toLowerCase()){
                result.status = 1;
                result.msg = "校验成功"
                result.uid = rows[0].uid;
                result.index_url = rows[0].index_url;
                defered.resolve(result);
            }else{
                result.status = 0;
                result.msg = "密码错误";
                defered.resolve(result);
            }

        }else{
            result.status = 0;
            result.msg = "用户不存在";
            defered.resolve(result);
        }
    },function(err){
        console.log(err)
    });

    return defered.promise;
}

/**
 * 判断用户是否存在
 * @param email
 * @returns {promise}
 */
UserService.prototype.userExists = function(email){
    var defered = Q.defer();
	console.log("SELECT * FROM user WHERE email='"+email+"'");
    mysqlService.select("SELECT * FROM user WHERE email='"+email+"'").then(function(rows){
	console.log(rows);
        if(rows.length>0){
            defered.resolve(true);
        }else{
            defered.resolve(false);
        }
    },function(err){
	console.log(err);
        defered.reject(err);
    });
    return defered.promise;
}

UserService.prototype.isLogin = function(req,res){
    var map = {};
    map.time = req.cookies.time ;
    map.email = req.cookies.email ;
    map.sign = req.cookies.sign ;
    map.uidCrypt = req.cookies.uidCrypt;

    if(!this._isLogin(map)){
        return res.redirect(301, "/login");
    }
}
/**
 * 判断用户是否登录
 * @param map {time:登录的时间戳,email:'登录的email',sign:'生成的验证字符'}
 * @returns {boolean}
 */
UserService.prototype._isLogin = function(map){
    var time = map.time;
    var email = map.email;
    try{
        var uid = mcryptService.decode(map.uidCrypt);
    }catch (err){
        return false;
    }
    var sign = crypto.createHash('md5').update(loginKey+time+email, 'utf8').digest("hex");
    if(sign==map.sign){
        return true;
    }else{
        return false;
    }
}


UserService.prototype.setIndexUrl = function(uid,url){
    var defered = Q.defer();
    mysqlService.update("UPDATE user SET index_url='"+url+"' WHERE uid="+uid).then(
        function(changedRows){
            defered.resolve(changedRows);
        },
        function(err){
            defered.reject(err);
        }
    );
    return defered.promise;
}